package com.cet.juc;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @program: cet-practice
 * @description:
 * @author: 陈恩涛
 * @create: 2023-07-02 23:42
 **/
public class SemaphoreTest {

    private static final Long BATCH_SIZE = 1000L;

    public static void main(String[] args) {

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors(),
            Runtime.getRuntime().availableProcessors() * 2,
            60,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(10 * Runtime.getRuntime().availableProcessors()),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.CallerRunsPolicy()
        );

        Semaphore semaphore = new Semaphore(1);

        // startIndex get from db
        // select id from table order by id limit 1;

        long minId = 0L;

        AtomicLong startIndex = new AtomicLong(minId);

        threadPoolExecutor.execute(() -> {

            Long oldStartIndex = startIndex.get();

            try {
                semaphore.acquire();

                // select id from table where id >= startIndex limit batch_size + 1;
                // update start index
                // startIndex = idList.get(batch_size);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                semaphore.release();
            }

            processDataWithStartIndex(oldStartIndex);
        });
    }

    private static void processDataWithStartIndex(Long oldStartIndex) {

    }
}

